#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" By Martin Senande-Rivera
    For Towards and atmosphere more favourable to firestorm development in Europe """

import os
import glob, sys
import numpy as np
import xarray as xr
import pandas as pd
from scipy import stats

path_outs='./ERA5/'

# Number of days with FWI above the threshold
FWI = xr.open_dataset(path_outs+'FWI_ndays.nc')['fwi']

# Linear trend function
def linear_trend(x):
    pf = np.polyfit(np.arange(1979.,2020.), x, 1)
    return xr.DataArray(pf[0])
# p-values function
def pvalue(x):
    r, p = stats.pearsonr(np.arange(1979.,2020.), x)
    return xr.DataArray(p)

FWI.values[np.isnan(FWI)]=-999.

# Linear trend of the number of days with FWI above the threshold
trend = xr.apply_ufunc(linear_trend,  # function to apply
                         FWI,
                         input_core_dims=(('time',),),
                         vectorize=True) 
trend.to_netcdf(path_outs+'FWI_ndays_trend.nc')

# p-values of the number of days with FWI above the threshold
pvalues = xr.apply_ufunc(pvalue,  # function to apply
                         FWI,
                         input_core_dims=(('time',),),
                         vectorize=True) 
pvalues.to_netcdf(path_outs+'FWI_ndays_pvalues.nc')


